package controller

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "ginweb/internal/service/command"
    "ginweb/internal/service/query"
    "ginweb/pkg/validator"
    "ginweb/internal/domain/product"
)

type ProductController struct {
    productService *command.ProductService
    queryService *query.ProductService
}

func NewProductController(productService *command.ProductService, queryService *query.ProductService) *ProductController {
    return &ProductController{productService: productService, queryService: queryService}
}

func (c *ProductController) CreateProduct(ctx *gin.Context) {
    var product product.Product
    if err := validator.BindAndValidate(ctx, &product); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := c.productService.CreateProduct(&product); err != nil {
        ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    ctx.JSON(http.StatusCreated, gin.H{"message": "Product created", "product": product})
}

func (c *ProductController) GetProduct(ctx *gin.Context) {
    id := ctx.Param("id")
    product, err := c.queryService.GetProduct(id)
    if err != nil {
        ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    ctx.JSON(http.StatusOK, gin.H{"product": product})
}

func (c *ProductController) UpdateProduct(ctx *gin.Context) {
    var product product.Product
    if err := validator.BindAndValidate(ctx, &product); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := c.productService.UpdateProduct(&product); err != nil {
        ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    ctx.JSON(http.StatusOK, gin.H{"message": "Product updated", "product": product})
}

func (c *ProductController) DeleteProduct(ctx *gin.Context) {
    id := ctx.Param("id")
    if err := c.productService.DeleteProduct(id); err != nil {
        ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    ctx.JSON(http.StatusOK, gin.H{"message": "Product deleted"})
}